package com.example.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.entity.User;
import com.example.service.SendEmailService;
import com.example.service.UserService;
import com.example.utils.*;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.mail.MessagingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/user")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private SendEmailService sendEmailService;

    @PostMapping("/login")
    public ExceptionResult login(@RequestBody UserDTO userDTO){
        if("".equals(userDTO.getAccount())){
            throw new AMSException(ExceptionEnum.loginname_cannot_bu_null);
        }
        UserDTO dto = userService.login(userDTO);
        if(dto == null){
            return new ExceptionResult(500,"登陆失败",null);
        }else {
            return new ExceptionResult(200,"成功", dto);
        }
    }

    //新增与修改同一个方法
    @PostMapping
    public ExceptionResult save(@RequestBody User user) {
        if (user.getId() == null){
            //新增进行密码加密
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            user.setCreatetime(new Date());
            return ExceptionResult.success(userService.save(user));
        }else {
            return ExceptionResult.success(userService.saveOrUpdate(user));
        }
    }
    //修改密码接口
    @PostMapping("/updatepassword")
    public ExceptionResult updatepassword(@RequestParam Integer id,
                                          @RequestParam String newpassword) {
        User byId = userService.getById(id);
        byId.setPassword(newpassword);
        return ExceptionResult.success(userService.saveOrUpdate(byId));
    }
    //通过邮箱获取验证码
    @GetMapping("/email/{email}")
    public ExceptionResult forget(@PathVariable String email) throws MessagingException {
        QueryWrapper<User> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("email",email);
        User user = userService.getOne(queryWrapper);
        if (user==null){
            return ExceptionResult.error(400,"该邮箱没有被注册进本系统中");
        }else{
            Map<String,String> map = new HashMap<>();
            map.put("email",sendEmailService.sendEmail(email));
            map.put("userid", String.valueOf(user.getId()));
            return ExceptionResult.success(map);
        }
    }

    //注册方法
    @PostMapping("/register")
    public ExceptionResult register(@RequestBody User user) {
        //通过注册的默认为普通用户
        user.setRoleid(1);
        user.setCreatetime(new Date());
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account",user.getAccount());
        List<User> list = userService.list(queryWrapper);
        if (list.size()>0){
            return ExceptionResult.error(201,"用户名已存在请更改用户名!");
        }
        QueryWrapper<User> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("email",user.getEmail());
        List<User> list1 = userService.list(queryWrapper1);
        if (list1.size()>0){
            return ExceptionResult.error(202,"当前邮箱已经注册账号请重新填写!");
        }
        return ExceptionResult.success(userService.save(user));
    }

    //删除
    @DeleteMapping("/{id}")
    public ExceptionResult delete(@PathVariable Integer id) {
        return ExceptionResult.success(userService.removeById(id));
    }

    //查询列表
    @GetMapping
    public ExceptionResult findAll() {
        return ExceptionResult.success(userService.list());
    }

    //根据id查询单个
    @GetMapping("/{id}")
    public ExceptionResult findOne(@PathVariable Integer id) {
        return ExceptionResult.success(userService.getById(id));
    }

    //批量删除
    @PostMapping("/del/batch")
    public ExceptionResult deleteBatch(@RequestBody List<Integer> ids){
        return ExceptionResult.success(userService.removeByIds(ids));
    }
    //获取用户数量
    @GetMapping("/count")
    public ExceptionResult getUserCount(){
        return ExceptionResult.success(userService.getUserCount());
    }
    //分页查询
    @GetMapping("/page")
    public ExceptionResult findPage(@RequestParam Integer pageNum,
                                    @RequestParam Integer pageSize,
                                    @RequestParam(defaultValue = "") String account,
                                    @RequestParam(defaultValue = "") String address) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(!"".equals(account), User::getAccount,account);
        queryWrapper.like(!"".equals(address), User::getAddress,address);
        queryWrapper.orderByDesc(User::getId);
        return ExceptionResult.success(userService.page(new Page<>(pageNum, pageSize),queryWrapper));
    }
}
